﻿using LSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ServerDemo {
    public partial class ServerForm : Form {
        public ServerForm() {
            InitializeComponent();
            this.Text = "Server";
        }

        private void ServerForm_Load(object sender, EventArgs e) {
            LSocketManager.OnAcceptClient += LSocketManager_OnAcceptClient;
            LSocketManager.OnReceived += LSocketManager_OnReceived;
            LSocketManager.OnClientClose += LSocketManager_OnClientClose;
            LSocketManager.Start();
        }

        private void LSocketManager_OnClientClose(LClient obj) {
            listBox1.Invoke((Action)delegate () { listBox1.Items.Remove(obj); });
        }

        private void LSocketManager_OnAcceptClient(LClient obj) {
            listBox1.Invoke((Action)delegate () { listBox1.Items.Add(obj); });
        }

        private void LSocketManager_OnReceived(LMessage obj) {
            string msg = obj.client.ToString() + " " + DateTime.Now.ToString("HH:mm:ss");
            msg += "\r\n";
            msg += Encoding.Unicode.GetString(obj.newCmd, 0, obj.newCmd.Length);
            msg += "\r\n";
            richTextBox1.Invoke((Action)delegate () { richTextBox1.Text += msg; });
        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) {
            int index = listBox1.IndexFromPoint(e.Location);
            if (index < 0)
                return;
            LClient client = listBox1.Items[index] as LClient;
            byte[] testCmd = Encoding.Unicode.GetBytes("Hello LSocket Client");
            LSocketManager.Send(client, testCmd);
        }

        private void button1_Click(object sender, EventArgs e) {
            LSocketManager.SendToAllClient(Encoding.Unicode.GetBytes("This is a broadcast from lsocket server"));
        }
    }
}
